package com.jin.lazytool.listener;

import com.github.kwhat.jnativehook.GlobalScreen;
import com.github.kwhat.jnativehook.mouse.NativeMouseEvent;
import com.github.kwhat.jnativehook.mouse.NativeMouseMotionListener;
import com.jin.lazytool.entity.MouseMotionEvent;
import com.jin.lazytool.utils.ConfigUtils;
import com.jin.lazytool.utils.CurrentStateUtil;
import java.awt.*;
import java.util.Timer;
import java.util.TimerTask;

public class MouseMotionListener implements NativeMouseMotionListener {

    private boolean mouseAddFlag = false;
    private NativeMouseEvent preNativeMouseEvent;
    private Timer timer = new Timer();


    private boolean mouseAddDragFlag = false;
    private NativeMouseEvent preNativeMouseDragEvent;
    private Timer timerDrag = new Timer();

    // true 移动；false 拖拽
    private boolean moveOrDrag = true;


    public MouseMotionListener(){
        init();
    }

    private final TimerTask task = new TimerTask() {
        @Override
        public void run() {
            if(preNativeMouseEvent == null || !moveOrDrag){
                return;
            }
            PointerInfo pointerInfo = MouseInfo.getPointerInfo();
            Point location = pointerInfo.getLocation();
            if(location.equals(preNativeMouseEvent.getPoint()) && !mouseAddFlag){
                CurrentStateUtil.addEventOfGroup(new MouseMotionEvent(preNativeMouseEvent));
                mouseAddFlag = true;
            }
        }
    };
    private final TimerTask taskDrag = new TimerTask() {
        @Override
        public void run() {
            if(preNativeMouseDragEvent == null || moveOrDrag){
                return;
            }
            PointerInfo pointerInfo = MouseInfo.getPointerInfo();
            Point location = pointerInfo.getLocation();
            if(location.equals(preNativeMouseDragEvent.getPoint()) && !mouseAddDragFlag){
                CurrentStateUtil.addEventOfGroup(new MouseMotionEvent(preNativeMouseDragEvent));
                mouseAddDragFlag = true;
            }
        }
    };
    private void init(){
        timer.schedule(task,0, ConfigUtils.getMouseMoveTime());
        timerDrag.schedule(taskDrag,0, ConfigUtils.getMouseDragTime());
    }

    public void destroy(){
        timer.cancel();
        GlobalScreen.removeNativeMouseMotionListener(this);
    }

    @Override
    public void nativeMouseMoved(NativeMouseEvent nativeMouseEvent) {
        preNativeMouseEvent = nativeMouseEvent;
        mouseAddFlag = false;
        moveOrDrag = true;
    }

    @Override
    public void nativeMouseDragged(NativeMouseEvent nativeMouseEvent) {
        preNativeMouseDragEvent = nativeMouseEvent;
        mouseAddDragFlag = false;
        moveOrDrag = false;
    }
}
